import React, { useState } from 'react'
import classNames from 'classnames'
import { useTranslation } from 'react-i18next'
import { isPromise } from '@/library/tool-kits/is-valid'
import { usePropsValue } from '../../hooks/use-props-value'
import { withNativeProps } from '../../utils/native-props'
import SpinIcon from './spin-icon'
import { SwitchProps } from './type'

const classPrefix = 'rt-switch'

export const Switch: React.FC<SwitchProps> = (props) => {
  const {
    checked,
    checkedText,
    defaultChecked = false,
    disabled = false,
    loading = false,
    onChange,
    uncheckedText,
  } = props

  const { t: translate } = useTranslation()

  const [changing, setChanging] = useState(false)

  const [actChecked, setActChecked] = usePropsValue({
    value: checked,
    defaultValue: defaultChecked,
    onChange,
  })

  const onClick = async () => {
    if (disabled || loading || changing) {
      return
    }

    const result = setActChecked(!actChecked)

    if (isPromise(result)) {
      setChanging(true)
      try {
        await result
        setChanging(false)
      } catch (e) {
        setChanging(false)
        throw e
      }
    }
  }

  return withNativeProps(
    props,
    <div
      onClick={onClick}
      className={
        classNames(
          classPrefix, {
            [`${classPrefix}-checked`]: actChecked,
            [`${classPrefix}-disabled`]: disabled || loading || changing,
          },
        )
      }
      role="switch"
      aria-label={translate('common.gallery.Switch.name')}
      tabIndex={0}
      aria-checked={actChecked}
      aria-disabled={disabled || loading}
    >
      <div className={`${classPrefix}-checkbox`}>
        <div className={`${classPrefix}-handle`}>
          {(loading || changing) && (
            <SpinIcon className={`${classPrefix}-spin-icon`} />
          )}
        </div>
        <div className={`${classPrefix}-inner`}>
          {actChecked ? checkedText : uncheckedText}
        </div>
      </div>
    </div>,
  )
}
